package org.xx.armory.rpc;

import javax.management.openmbean.CompositeData;

import static org.xx.armory.commons.Validators.notNull;

public class WorkThreadInfo {
    private final long id;
    private final String name;
    private final String groupName;
    private final String state;
    private final String stackTrace;

    public WorkThreadInfo(
            Thread thread
    ) {
        notNull(thread, "thread");

        this.id = thread.getId();
        this.name = thread.getName();
        final ThreadGroup threadGroup = thread.getThreadGroup();
        this.groupName = threadGroup != null ? threadGroup.getName() : "";
        this.state = String.valueOf(thread.getState());

        final StringBuilder stBuilder = new StringBuilder();
        final StackTraceElement[] stackTraceElements = thread.getStackTrace();
        if (stackTraceElements.length > 0) {
            stBuilder.append(stackTraceElements[0]).append('\n');
        }
        for (int i = 1; i < stackTraceElements.length; ++i) {
            stBuilder.append(stackTraceElements[i]).append('\n');
        }
        this.stackTrace = stBuilder.toString();
    }

    public WorkThreadInfo(
            CompositeData data
    ) {
        notNull(data, "data");

        this.id = (long) data.get("id");
        this.name = (String) data.get("name");
        this.groupName = (String) data.get("groupName");
        this.state = (String) data.get("state");
        this.stackTrace = (String) data.get("stackTrace");
    }

    public WorkThreadInfo(
            long id,
            String name,
            String groupName,
            String state,
            String stackTrace
    ) {
        this.id = id;
        this.name = name;
        this.groupName = groupName;
        this.state = state;
        this.stackTrace = stackTrace;
    }

    public final long getId() {
        return this.id;
    }

    public final String getName() {
        return this.name;
    }

    public final String getGroupName() {
        return this.groupName;
    }

    public final String getState() {
        return this.state;
    }

    public final String getStackTrace() {
        return this.stackTrace;
    }


}
